package com.example.service;

import com.example.POJO.Order;
import com.example.mapper.OrderMapper;
import com.example.mapper.UserMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

@Service
public class OrderService {
    public String addShoppingCast(Order order) throws IOException {
        try{
            String resource= "mybatis-config.xml";
            InputStream inputStream= Resources.getResourceAsStream(resource);
            SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
            SqlSession sqlSession=sqlSessionFactory.openSession(true);

            OrderMapper orderMapper=sqlSession.getMapper(OrderMapper.class);
            orderMapper.insertOrder(order);

            sqlSession.close();
            return "true";
        }catch (Exception e){
            System.out.println(e);
            return "false";
        }
    }

    public List<Order> getOrderByUserId(Integer user_id) throws IOException {
        String resource= "mybatis-config.xml";
        InputStream inputStream= Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession=sqlSessionFactory.openSession();

        OrderMapper orderMapper=sqlSession.getMapper(OrderMapper.class);
        List<Order> orders=orderMapper.getOrderByUserId(user_id);

        sqlSession.close();
        return orders;
    }

    public void setSubmitted(Integer order_id) throws IOException {
        String resource= "mybatis-config.xml";
        InputStream inputStream= Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession=sqlSessionFactory.openSession(true);

        OrderMapper orderMapper=sqlSession.getMapper(OrderMapper.class);
        orderMapper.setSubmitted(order_id);

        sqlSession.close();
    }

    public List<Order> getSubmittedOrderByUserId(Integer user_id) throws IOException {
        String resource= "mybatis-config.xml";
        InputStream inputStream= Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession=sqlSessionFactory.openSession();

        OrderMapper orderMapper=sqlSession.getMapper(OrderMapper.class);
        List<Order> orders=orderMapper.getSubmittedOrderByUserId(user_id);

        sqlSession.close();
        return orders;
    }
}
